import axios from 'axios';
import { Toast, Notify } from 'vant';
import { getItem } from '@/plugins';
import store from '@/store';
import router from '@/router';
const token = getItem('access_key');
const api = axios.create({
  baseURL: process.env.VUE_APP_API_ROOT,
  withCredentials: false, //cookie 设置
  maxRedirects: 5,
  timeout: 30*1000,
});

api.interceptors.request.use(
  (config) => {
    if (token) {
      config.headers['token'] = getItem('access_key') || '';
      config.headers['Accept-Language'] = getItem('lang')
        ? getItem('lang').value
        : 'en';
    } else {
      if (store.state.token) {
        config.headers['token'] = store.state.token;
      }
      config.headers['Accept-Language'] = getItem('lang')
        ? getItem('lang').value
        : 'en';
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 相应拦截器
api.interceptors.response.use(
  (response) => {
    const code = response.data.code;
    switch (code) {
      case 1: {
        return response.data;
      }
      case 404: {
        Toast.fail(response.data.msg);
        return Promise.reject(response.data);
      }
      case 401: {
        router.push({ path: '/login', query: { n: 1 } });
        return Promise.reject(response.data);
      }
      case 0: {
        if (response.config.url.indexOf('merchant/index') !== -1) {
          return response.data;
        } else {
          // response.data.data ? response.data.data=JSON.parse(decrypt(response.data.data)) : response.data=response.data.data
          return Promise.reject(response.data);
        }
      }
      default: {
        if (window.navigator && navigator.onLine === true) {
          Toast.fail(response.data.msg);
        } else {
          // Toast(setting.public.onLine[lang])
        }
        return Promise.reject(response.data);
      }
    }
  },
  (error) => {
    if(error?.response?.data?.code === 401){
      router.replace({ path: '/login', query: { n: 1 } });
    }else{
        Toast.fail(error.message);
    }
    return Promise.reject(error);
  }
);

export default api;
